#!/bin/bash
export HOMEDIR=$(dirname $(dirname $(readlink -f "${BASH_SOURCE[0]}")))
source $HOMEDIR/scripts/init-env.sh
schema_list=($(jq -r '.object.schemas[]' $HOMEDIR/config/mtk-config.json))
printf -v schema_string1 "'%s'," "${schema_list[@]}"
schema_string1=${schema_string1%,}

cd $HOMEDIR/workspace/mtk
$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --target -C "
DO LANGUAGE 'plpgsql'
\$BODY\$
begin
raise notice 'start compile';
for rec in (select 'ALTER PACKAGE ' || owner || '.' || object_name || ' COMPILE BODY;' as cmd
 from dba_objects t
 where t.status = 'INVALID'
 and t.object_type = 'PACKAGE BODY'
 and upper(t.owner) in ($schema_string1)
UNION all
 select 'ALTER VIEW ' || owner || '.' || object_name || ' COMPILE;' as cmd
 from dba_objects t
 where t.status = 'INVALID'
 and t.object_type = 'VIEW'
 and upper(t.owner) in ($schema_string1)) loop
  raise notice '%',rec.cmd;
  execute immediate rec.cmd;
  commit;
  end loop;
  raise notice 'finish compile';
  end;
\$BODY\$
"